using System;
using System.Collections.Generic;
using System.Globalization;

namespace Microsoft.Xna.Framework
{
	public class GameServiceContainer : IServiceProvider
	{
		private readonly Dictionary<Type, object> _services = new Dictionary<Type, object>();

		public void AddService(Type type, object provider)
		{
			if (type == null)
				throw new ArgumentNullException("type", Resources.ServiceTypeCannotBeNull);
			if (provider == null)
				throw new ArgumentNullException("provider", Resources.ServiceProviderCannotBeNull);
			if (_services.ContainsKey(type))
				throw new ArgumentException(Resources.ServiceAlreadyPresent, "type");
			if (!type.IsInstanceOfType(provider))
				throw new ArgumentException(string.Format(CultureInfo.CurrentUICulture,
														  Resources.ServiceMustBeAssignable,
														  new object[]
				                                          	{
				                                          		provider.GetType().FullName,
				                                          		type.GetType().FullName
				                                          	}));
			else
				_services.Add(type, provider);
		}

		public void RemoveService(Type type)
		{
			if (type == null)
				throw new ArgumentNullException("type", Resources.ServiceTypeCannotBeNull);
			_services.Remove(type);
		}

		public object GetService(Type type)
		{
			if (type == null)
				throw new ArgumentNullException("type", Resources.ServiceTypeCannotBeNull);
			if (_services.ContainsKey(type))
				return _services[type];
			else
				return null;
		}

		public void AddService<T>(T service)
		{
			AddService(typeof(T), service);
		}

		public void RemoveService<T>()
		{
			RemoveService(typeof(T));
		}

		public T GetService<T>() where T : class
		{
			return GetService(typeof(T)) as T;
		}
	}
}